﻿#include <iostream>
#include <list>
using namespace std;

#include "guard.h"

class Object
{
public:
    Object()
    {
    }

    virtual ~Object()
    {
    }

    Guard GetObjectGuard()
    {
        return m_guard;
    }

private:
    Guard m_guard;
};

class Listener : public Object
{
public:
    Listener()
    {
    }

    virtual ~Listener()
    {
    }

    virtual void Func() = 0;
};

class AListener : public Listener
{
public:
    AListener()
    {
    }

    ~AListener()
    {
    }

    virtual void Func()
    {
        std::cout << "AListener Func" << std::endl;
    }
};

class BListener : public Listener
{
public:
    BListener()
    {
    }

    ~BListener()
    {
    }

    virtual void Func()
    {
        std::cout << "BListener Func" << std::endl;
    }
};

class Notify
{
public:
    void DoAll()
    {
        for (auto ite = m_listeners.begin(); ite != m_listeners.end(); ++ite)
        {
            if ((*ite))
            {
                (*ite)->Func();
            }
            else
            {
                std::cout << "guardpointer guard fail!" << std::endl;
            }
        }
    }

    void RegisterListener(Listener *listener)
    {
        m_listeners.push_back(GuardPointer<Listener>(listener));
    }

private:
    std::list<GuardPointer<Listener>> m_listeners;
};

int main()
{
    Notify notify;

    Listener *p1 = new AListener();
    Listener *p2 = new AListener();
    Listener *p3 = new BListener();
    Listener *p4 = new BListener();

    notify.RegisterListener(p1);
    notify.RegisterListener(p2);
    notify.RegisterListener(p3);
    notify.RegisterListener(p4);

    notify.DoAll();

    delete p2;
    notify.DoAll();

    delete p1;
    delete p3;
    notify.DoAll();

    delete p4;
    notify.DoAll();

    return 0;
}
